from flask import current_app, jsonify
from flask import g
from flask import request
from flask import session

from info.commons import user_login_data
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index_blue
from flask import render_template


@index_blue.route("/", methods=['GET', 'POST'])
@user_login_data
def show_index():
    # # 1.获取session用户编号
    # user_id = session.get('user_id')
    # # 2.根据用户编号获取对象
    # user = None
    # if user_id:
    #     user = User.query.get(user_id)
    # 3.按照点击量查询前10条新闻
    try:
        news_list = News.query.order_by(News.clicks).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
    # 将新闻对象列表转换为新闻的字典列表
    click_news_list = []

    for news in news_list:
        click_news_list.append(news.to_dict())

    # 4.查询所有分类，转成字典列表
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    categories_list = []
    for category in categories:
        categories_list.append(category.to_dict())

    # 3.携带数据，渲染页面
    dict_data = {
        'user_info': g.user.to_dict() if g.user else "",
        "click_news_list": click_news_list,
        "categories_list": categories_list
    }
    return render_template('news/index.html', dict_data=dict_data)


@index_blue.route("/favicon.ico")
def get_logo():
    response = current_app.send_static_file('news/favicon.ico')
    return response


@index_blue.route("/newslist")
def news_list():
    # 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '5')
    # 参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 5
    try:
        condition = ""
        if cid != '1':
            condition = (News.category_id == cid)

        paginate = News.query.filter(condition).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取新闻数据失败')
    totalPage = paginate.pages
    items = paginate.items
    currentPage = paginate.page

    newsList = []
    for news in items:
        newsList.append(news.to_dict())

    return jsonify(errno=RET.OK, errmsg="获取数据成功", totalPage=totalPage, currentPage=currentPage, newsList=newsList)

